﻿/*
 * @author Rui Zhong
 */

/**
通知，转菊花等组件
**/
var Toolbox = (function (toolbox) {
    return toolbox;
}(Toolbox || {}));

Toolbox.Notifier = (function (toolboxNotifier) {
    var self = toolboxNotifier;

    self.message = function (type, message) {
        toastr.options = {
            "closeButton": true,
            "onclick": null,
            "debug": false,
            "positionClass": "toast-top-center",
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "-1",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        toastr[type](message);
    };

    self.success = function (message) {
        self.message("success", message);
    };

    self.info = function (message) {
        self.message("info", message);
    };

    self.warning = function (message) {
        self.message("warning", message);
    };

    self.error = function (message) {
        self.message("error", message);
    };

    return self;
})(Toolbox.Notifier || {});

Toolbox.Model = (function (toolboxModel) {
    var self = toolboxModel;

    $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner = '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="progress-bar" style="width: 100%;"></div></div></div>';
    $.fn.modalmanager.defaults.resize = true;

    self.showLoading = function () {
        $("body").modalmanager("loading");
    };

    self.hideLoading = function () {
        $("body").modalmanager("removeLoading");
    };

    return self;
})(Toolbox.Model || {});


/**
其他自定义脚本，主要处理ajax
**/
; (function ($) {


    $.recoobAjaxPage = function () {

        //处理ajaxResult对象
        function dealWithAjaxResult(result) {
            if (result.Success === true) {
                for (var i = 0 ; i < result.Messages.length; i++) {
                    Toolbox.Notifier.success(result.Messages[i]);
                }
            }
            else {
                for (var i = 0 ; i < result.Messages.length; i++) {
                    Toolbox.Notifier.error(result.Messages[i]);
                }
            }

            var redirectUrl = "";
            if (result.ReloadPage) {
                redirectUrl = window.location.href;
            }
            else if (result.RedirectUrl) {
                redirectUrl = result.RedirectUrl;
            }

            if (redirectUrl) {
                setTimeout(function () {
                    window.location.href = redirectUrl;
                }, 500);
            }
        }

        //处理ajax链接
        var handleAjaxLink = function () {
            $(document).on("click", ".js-ajax-button", function () {
                var ajaxUrl = $(this).data("url");
                var ajaxMethod = $(this).data("method") ? $(this).data("method").toUpperCase() : "POST";
                var callback = $(this).data("callback");
                var valid = $(this).data("valid");
                if (valid && window[valid] && window[valid] instanceof Function) {
                    var msg = window[valid]();
                    if (msg) {
                        Toolbox.Notifier.error(msg);
                        return false;
                    }
                }

                var postData = {};
                //附加数据
                var getdata = $(this).data("getdata");
                if (getdata && window[getdata] && window[getdata] instanceof Function) {
                    postData = window[getdata]();
                }

                Toolbox.Model.showLoading();
                var ajaxOptions = {
                    url: ajaxUrl,
                    data: postData,
                    type: ajaxMethod,
                    error: function () {
                        Toolbox.Model.hideLoading();
                    },
                    success: function (result) {
                        Toolbox.Model.hideLoading();
                        dealWithAjaxResult(result);
                        if (callback && window[callback] && window[callback] instanceof Function) {
                            window[callback](result);
                        }
                    }
                };

                $.ajax(ajaxOptions);

                return false;
            })
        }

        //查询div的处理
        var handleSearch = function () {

            //重置按钮
            var $searchForm = $("#js-search-form");
            var $searchFormResetButton = $(".js-search-form-reset-button");
            $searchFormResetButton.click(function () {
                $("input[type=text]", $searchForm).val("");
                $("select", $searchForm).each(function () {
                    var $ele = $(this);
                    $ele.val("");
                    if ($ele.hasClass("select2")) {
                        $ele.trigger("change");
                    }
                });
                return false;
            });
        };

        //表格处理
        var handleDataTable = function () {

            //ajax操作按钮
            var $tableAjaxConfirmButton = $(".js-table-ajax-confirm-button");

            $tableAjaxConfirmButton.click(function () {
                var $self = $(this);

                var confirmText = $self.data("confirm-text");
                var confirmButton = $self.data("confirm-button");
                var cancelButton = $self.data("cancel-button");
                var confirmedUrl = $self.data("confirmed-url");
                var confirmTitle = $self.data("confirm-title");

                //提交前自定义扩展
                var confirmAttach = {};
                if (window.beforeAjaxFormSubmit instanceof Function
                    && false === window.beforeAjaxFormSubmit()) {
                    return false;
                }

                var confirmAttach = {};
                if (window.getConfirmAttachData instanceof Function) {
                    confirmAttach = window.getConfirmAttachData();
                }

                $.confirm({
                    title: confirmTitle,
                    text: confirmText,
                    confirmButton: confirmButton,
                    cancelButton: cancelButton,
                    confirmButtonClass: "btn-danger",
                    cancelButtonClass: "btn-default",
                    confirm: function () {
                        debugger
                        Toolbox.Model.showLoading();
                        $.post(confirmedUrl, confirmAttach, function (result) {
                            Toolbox.Model.hideLoading();
                            dealWithAjaxResult(result);
                        });
                    },
                    cancel: function () {
                    }
                });

                return false;
            });

            //表格明细展开缩小
            $(".dataTable").on("click", ".row-details.row-details-close", function () {
                var detailrow = $(this).parents("tr").next();
                while (detailrow.length && detailrow.hasClass("detail-row")) {
                    detailrow.show();
                    detailrow = detailrow.next();
                };
                $(this).removeClass("row-details-close").addClass("row-details-open");
            })
            $(".dataTable").on("click", ".row-details.row-details-open", function () {
                var detailrow = $(this).parents("tr").next();
                while (detailrow.length && detailrow.hasClass("detail-row")) {
                    detailrow.hide();
                    detailrow = detailrow.next();
                };
                $(this).removeClass("row-details-open").addClass("row-details-close");
            })
        };

        //表单处理
        var handleForm = function () {


            //$(".select2").each(function () {
            //    $this = $(this);
            //    var placeholder = $this.attr("placeholder");
            //    $this.select2({ width: '100%', placeholder: placeholder });
            //});

            $(".select2").each(function () {
                $this = $(this);
                var placeholder = $this.attr("placeholder");
                $this.select2({
                    width: '100%',
                    placeholder: placeholder,
                    templateResult: function (state) {
                        var txt = state.text;
                        if (txt.indexOf("*") == 0) {
                            return $('<span>&nbsp;&nbsp;&nbsp;&nbsp;' + txt.substring(1, txt.length) + '</span>');
                        }
                        else {
                            return $('<span><b>' + txt + '</b></span>');
                        }
                    }
                });
            });

            $(".form_datetime.year").datetimepicker({
                autoclose: true,
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd",
                minView: 'year', // 只选择到日期,不去选择时分秒
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                language: 'zh-CN', //汉化
            });
            $(".form_datetime.month").datetimepicker({
                autoclose: true,
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd",
                minView: 'month', // 只选择到日期,不去选择时分秒
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                language: 'zh-CN', //汉化
            });
            $(".form_datetime.day").datetimepicker({
                autoclose: true,
                isRTL: App.isRTL(),
                format: "yyyy-mm-dd",
                minView: 'day', // 只选择到日期,不去选择时分秒
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                language: 'zh-CN', //汉化
            });
            $(".form_datetime.hour").datetimepicker({
                autoclose: true,
                isRTL: App.isRTL(),
                format: "yyyy/mm/dd hh:ii:ss",
                minView: 'hour', // 只选择到日期,不去选择时分秒
                pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
                language: 'zh-CN', //汉化
            });

            handleFormValidationAdditionalMethods();

            var $form = $(".js-form");
            var formValidator = $form.validate();//依赖jQuery validate unobtrusive
            if (formValidator) {
                formValidator.settings.highlight = function (element, errorClass, validClass) {
                    $(element).closest(".form-group").addClass("has-error");
                };

                formValidator.settings.unhighlight = function (element, errorClass, validClass) {
                    $(element).closest(".form-group").removeClass("has-error");
                };

                // Server-side validation
                $(".field-validation-error").closest(".form-group").addClass("has-error");
            }

            var $ajaxForm = $(".js-ajax-form");
            $ajaxForm.submit(function () {
                var $self = $(this);

                //验证前自定义扩展
                if (window.beforeAjaxFormValidate instanceof Function
                    && false === window.beforeAjaxFormValidate()) {
                    return false;
                }

                if (!$self.valid()) {
                    return false;
                }

                Toolbox.Model.showLoading();

                //ckEditor插件更新数据
                if (window.CKEDITOR !== undefined && window.CKEDITOR.instances) {
                    for (instance in CKEDITOR.instances)
                        CKEDITOR.instances[instance].updateElement();
                }

                //uEditor表单提交
                //UE.instants.ueditorInstant0.sync($(this).attr("id"))
                if (window.UE !== undefined && window.UE.instants) {
                    for (instant in window.UE.instants) {
                        window.UE.instants[instant].sync();
                    }
                }

                //提交前自定义扩展
                if (window.beforeAjaxFormSubmit instanceof Function
                    && false === window.beforeAjaxFormSubmit()) {
                    return false;
                }

                var confirmAttach = {};
                if (window.getConfirmAttachData instanceof Function) {
                    confirmAttach = window.getConfirmAttachData();
                }


                var formUrl = $self.attr("action");
                var formType = $self.attr("method");
                var formMimeType = $self.attr("enctype");
                var formData = new FormData(this);

                var ajaxOptions = {
                    url: formUrl,
                    type: formType,
                    data: formData,
                    processData: false,
                    contentType: false,
                    error: function () {
                        Toolbox.Model.hideLoading();
                        Toolbox.Notifier.error("server error.");
                    },
                    success: function (result) {
                        Toolbox.Model.hideLoading();

                        if (formMimeType) {
                            result = JSON.parse(result);
                        }

                        if (result.Messages && result.Messages instanceof Array) {
                            if (result.Success === true) {
                                for (var i = 0 ; i < result.Messages.length; i++) {
                                    Toolbox.Notifier.success(result.Messages[i]);
                                }
                            }
                            else {
                                for (var i = 0 ; i < result.Messages.length; i++) {
                                    Toolbox.Notifier.error(result.Messages[i]);
                                }
                            }
                        }

                        var redirectUrl = "";
                        if (result.ReloadPage) {
                            redirectUrl = window.location.href;
                        }
                        else if (result.RedirectUrl) {
                            redirectUrl = result.RedirectUrl;
                        }

                        if (redirectUrl) {
                            setTimeout(function () {
                                window.location.href = redirectUrl;
                            }, 800);
                        }
                    }
                };

                if (formMimeType) {
                    ajaxOptions.mimeType = formMimeType;
                }

                $.ajax(ajaxOptions);

                return false;
            });
        };

        //验证函数
        var handleFormValidationAdditionalMethods = function () {

            jQuery.validator.addMethod("integer", function (value, element) {
                return this.optional(element) || /^-?\d+$/.test(value);
            }, "请输入正确的整数");

            jQuery.validator.addMethod("decimal", function (value, element) {
                return this.optional(element) || /^\d+(\.\d{0,3})?$/.test(value);
            }, "情输入正确的数字");
        };

        (function init() {
            handleSearch();
            handleDataTable();
            handleForm();
            handleAjaxLink();
        })();
    };
})(jQuery);

/*
 * @author xie40, 依赖jquery, jquery.form.js, layer.js
 */
; (function ($) {
    $.recoobHelper = {
        //确认弹窗
        confirm: function (text, confirmCallback, confirmText, cancelText) {
            if (!confirmText) {
                confirmText = "确定";
            }
            if (!cancelText) {
                cancelText = "取消";
            }
            $.confirm({
                title: '',
                text: text,
                confirmButton: confirmText,
                cancelButton: cancelText,
                confirmButtonClass: "btn-danger",
                cancelButtonClass: "btn-default",
                confirm: confirmCallback,
                cancel: function () {
                }
            });
        },
        //处理服务端定义的AjaxResult类
        ajaxResultCallback: function (result) {
            if (result.Messages && result.Messages instanceof Array) {
                if (result.Success === true) {
                    var msgStr = "";
                    for (var i = 0 ; i < result.Messages.length; i++) {
                        if (i !== 0) {
                            msgStr += "<br/>";
                        }
                        msgStr += result.Messages[i]
                    }
                    msgStr = $.trim(msgStr);
                    if (msgStr) {
                        Toolbox.Notifier.success(msgStr);
                    }
                }
                else {
                    var msgStr = "";
                    for (var i = 0 ; i < result.Messages.length; i++) {
                        if (i !== 0) {
                            msgStr += "<br/>";
                        }
                        msgStr += result.Messages[i]
                    }
                    msgStr = $.trim(msgStr);
                    if (msgStr) {
                        Toolbox.Notifier.error(msgStr);
                    }
                }
            }

            var redirectUrl = "";
            if (result.ReloadPage) {
                redirectUrl = window.location.href;
            }
            else if (result.RedirectUrl) {
                redirectUrl = result.RedirectUrl;
            }

            if (redirectUrl) {
                setTimeout(function () {
                    window.location.href = redirectUrl;
                }, 500);
            }
        },
        //ajax方式提交表单，简单包装了一层jquery.form.js
        sendAjaxForm: function ($form, extraData, callback, showLoading) {
            if (showLoading === undefined || showLoading) {
                Toolbox.Model.showLoading();
            }
            $form.ajaxSubmit({
                //timeout: 10000,
                data: extraData,
                error: function () {
                    if (showLoading === undefined || showLoading) {
                        Toolbox.Model.hideLoading();
                    }
                    Toolbox.Notifier.error("系统似乎暂时出现了错误~");
                },
                success: function (result) {
                    if (showLoading === undefined || showLoading) {
                        Toolbox.Model.hideLoading();
                    }
                    $.recoobHelper.ajaxResultCallback(result);
                    //回调函数
                    if (callback && callback instanceof Function) {
                        callback(result);
                    }
                }
            });
        },
        //扩展的ajax函数
        send: function (method, url, data, callback, ajaxExtra, showLoading) {
            showLoading = showLoading === undefined || showLoading;
            if (showLoading) {
                Toolbox.Model.showLoading();
            }
            if (method) {
                method = method.toUpperCase();
            }

            var ajaxOptions = {
                type: method,
                url: url,
                dataType: "json",
                data: data,
                //timeout: 10000,
                error: function () {
                    if (showLoading) {
                        Toolbox.Model.hideLoading();
                    }
                    Toolbox.Notifier.error("系统似乎暂时出现了错误~");
                },
                success: function (result) {
                    if (showLoading) {
                        Toolbox.Model.hideLoading();
                    }
                    if (ajaxExtra && ajaxExtra.mimeType) {
                        result = JSON.parse(result);
                    }

                    $.recoobHelper.ajaxResultCallback(result);

                    //回调函数
                    if (callback && callback instanceof Function) {
                        callback(result);
                    }
                }
            };

            if (ajaxExtra) {
                ajaxOptions = $.extend(ajaxOptions, ajaxExtra);
            }

            $.ajax(ajaxOptions);
        },
        //发送post请求
        post: function (url, data, callback, ajaxExtra, showLoading) {
            this.send("POST", url, data, callback, ajaxExtra, showLoading);
        },
        //发送get请求
        get: function (url, data, callback, ajaxExtra, showLoading) {
            this.send("GET", url, data, callback, ajaxExtra, showLoading);
        },

        searchSelect2: function ($selector, searchType, url) {
            $selector.select2({
                allowClear: true,
                ajax: {
                    url: url,
                    dataType: 'json',
                    delay: 500,
                    width: 'style',//width style
                    data: function (params) {
                        params.size = 30;
                        //已选中的id传回后台，使其下一次查询时候过滤掉
                        params.excludeIds = $selector.val();
                        params.type = searchType;//获取的数据类型

                        return params
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        data.pagination = {
                            more: (params.page * params.size) < data.count
                        };
                        return data
                    },
                    cache: true
                },
                minimumInputLength: 1
            });
        }
    };

    $('.js-ajax-select2-search').each(function () {
        var $this = $(this);
        var searchUrl = $this.data('url');
        var searchType = $this.data('type');
        $.recoobHelper.searchSelect2($this, searchType, searchUrl);
    });

})(jQuery);